package com.structure.project.common.utils;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.structure.project.common.error.ExceptionFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.http.MediaType;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.multipart.MultipartResolver;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

public class HttpRequestUtils {
    public static HttpServletRequest getHttpServletRequest(ServletRequest servletRequest) {
        String contentType = servletRequest.getContentType();
        if (StringUtils.isNotBlank(contentType) && contentType.contains(MediaType.MULTIPART_FORM_DATA_VALUE)) {
            // 注意：MultipartResolver springboot 已经默认注入了，如果没有的话，需要手动注入
            // 如果不使用MultipartResolver那么request.getParameter(name)，就获取不到参数，这里spring帮我们做了参数解析
            return getBean(servletRequest.getServletContext(), MultipartResolver.class).resolveMultipart((HttpServletRequest) servletRequest);
        }
        return (HttpServletRequest) servletRequest;
    }

    public static <T> T getBean(ServletContext sc, Class<T> requiredType) {
        ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(sc);
        return Objects.requireNonNull(ctx).getBean(requiredType);
    }

    public static HttpServletRequest getHttpServletRequest() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (ObjectUtils.isEmpty(requestAttributes)) {
            throw ExceptionFactory.instanceServerException("获取HttpServletRequest失败");
        }
        HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
        return request;
    }

    public static String getUri() {
        HttpServletRequest httpServletRequest = getHttpServletRequest();
        return httpServletRequest.getRequestURI();
    }
}
